package com.test.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zxs
 * @since 2021/5/7
 */
public class NettyServer {

    private final int port;

    private final Map<String, Integer> heartbeatMap = new ConcurrentHashMap<>();

    public NettyServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new IdleStateHandler(5, 0, 0))
                                    .addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4,0,4))
                                    .addLast(new StringDecoder())
                                    .addLast(new HeartbeatHandler(NettyServer.this));
                        }
                    });
            //开启服务
            ChannelFuture f = serverBootstrap.bind(port).sync();
            //关闭服务
            f.channel().closeFuture().sync();
        } finally {
            System.out.println("server shutdown");
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    static class HeartbeatHandler extends SimpleChannelInboundHandler<String> {

        private final NettyServer server;

        public HeartbeatHandler(NettyServer server){
            this.server = server;
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            server.heartbeatMap.put(ctx.channel().remoteAddress().toString(), 0);
            super.channelActive(ctx);

        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state().equals(IdleState.READER_IDLE)) {
                Integer count = server.heartbeatMap.get(ctx.channel().remoteAddress().toString());
                if (count == 2) {
                    ctx.close().addListener((ChannelFutureListener) future -> {
                        System.out.println("disconnect from " + ctx.channel().remoteAddress());
                        ctx.channel().parent().close();
                    });
                } else {
                    count++;
                    System.out.println(ctx.channel().remoteAddress().toString() + ": " + count);
                    server.heartbeatMap.put(ctx.channel().remoteAddress().toString(), count);
                }
            } else {
                super.userEventTriggered(ctx, evt);
            }
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println(msg);
        }
    }


    @SneakyThrows
    public static void main(String[] args) {
        new NettyServer(8080).run();

    }
}
